var express = require('express');
var router = express.Router();
var connection = require('../db/sql.js'); // 确保正确引入 connection 对象
var user  = require('../db/userSql.js');

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/login', function(req, res, next) {
  let params = {
    userName: req.body.userName,
    userPwd: req.body.userPwd
  }
  connection.query(user.queryUserName(params), function (error, result, fileds) {
    if (result.length > 0) {
      connection.query(user.queryUserPwd(params), function (err, result) {
        if (result.length > 0) {
          // let formattedBirthday = result[0].birthday.toISOString().split('T')[0];
          res.send({
            data: {
              success: true,
              msg: '登录成功',
              data: {
                userName: result[0].username, // 返回用户名
                img_url: result[0].img_url, // 返回用户头像
                // birthday: formattedBirthday,
                birthday: result[0].birthday.toISOString().split('T')[0],
                sex: result[0].sex,
                phone: result[0].phone,
                isVip:  result[0].is_vip
              }
            }
          })
        } else {
          res.send({
            data: {
              success: false,
              msg: '用户名或密码错误'
            }
          })
        }
      });
    } else {
      res.send({
        data: {
          success: false,
          msg: '用户不存在'
        }
      })
    }
  })
});

module.exports = router;